import SysUtil from './utils/SysUtil'

const B = 1
const KB = 1024
const MB = KB * KB

const netInfo = async () => {
  const res0 = await SysUtil.netInterfaces()
  const ifaces = []
  const data0 = res0.filter((item) => {
    if (item.operstate === 'up' && !item.virtual && item.default) {
      ifaces.push(item.iface)
      return true
    }
    return false
  })
  const res1 = await SysUtil.netCheck(SysUtil.defaultChkUrls[0])
  // console.log(res1)
  let downRate = 0,
    upRate = 0
  if (res1.ok) {
    const res2 = await SysUtil.netStats(ifaces.join()).then((res2) => {
      // console.log(res2)
      downRate = res2[0].rx_sec
      upRate = res2[0].tx_sec
    })
  }

  return new Promise((resolve) => {
    resolve({
      status: res1.ok,
      downRate: calcNetRate(downRate),
      upRate: calcNetRate(upRate)
    })
  })
}

/**
 * 计算
 * @param bytes
 * @returns {string}
 */
const calcNetRate = (bytes) => {
  // console.log(`[bytes] = ${bytes}`)

  if (!bytes || bytes === 0 || bytes === Infinity) return '0 Kb/s'

  bytes = Math.floor(bytes)
  const mb = Math.floor(bytes / MB)
  let leftBs = bytes % MB
  const kb = Math.floor(leftBs / KB)

  // console.log(`mb=${mb}, left=${leftBs}, kb=${kb}`)

  let ret
  let dotRate
  if (mb !== 0) {
    if (kb !== 0) {
      dotRate = Math.floor(leftBs >= 1000 && leftBs < KB ? leftBs / KB / 100 : leftBs / KB / 10)
      ret = `${mb}.${dotRate} Mb/s`
    } else {
      ret = `${mb} Mb/s`
    }
  } else {
    leftBs = leftBs % KB
    if (kb !== 0) {
      dotRate = Math.floor(leftBs >= 1000 && leftBs < KB ? leftBs / B / 100 : leftBs / B / 10)
      ret = `${kb}.${dotRate} Kb/s`
    } else {
      ret = `${Math.floor(leftBs)} B/s`
    }
  }
  return ret
}

export { netInfo }
